<template>
  <div class="notification-wrapper" :class="{ 'has-notifications': unreadCount > 0 }">
    <div class="notification-counter" v-if="unreadCount > 0">
      {{ unreadCount > 99 ? '99+' : unreadCount }}
    </div>
    <el-popover
      placement="bottom-end"
      :visible-arrow="true"
      :offset="12"
      :show-after="0"
      :hide-after="0"
      trigger="manual"
      :teleported="true"
      :close-on-click-outside="false"
      popper-class="notification-popover"
      v-model:visible="popoverVisible"
    >
      <template #reference>
        <div class="notification-bell" @click="handleBellClick">
          <el-badge :is-dot="unreadCount > 0">
            <el-icon class="bell-icon"><Bell /></el-icon>
          </el-badge>
        </div>
      </template>
      <div class="notification-panel">
        <div class="notification-header">
          <div class="notification-title">订单通知</div>
          <div class="notification-actions">
            <el-button type="text" size="small" @click="markAllAsRead" v-if="unreadCount > 0">
              全部已读
            </el-button>
            <el-button type="text" size="small" @click="clearAll" v-if="notifications.length > 0">
              清空
            </el-button>
            <el-button type="text" size="small" @click="closeNotificationPanel">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="notification-content" v-if="notifications.length > 0">
          <div 
            v-for="notification in notifications" 
            :key="notification.id" 
            class="notification-item"
            :class="{ 'unread': !notification.read, 'reminder': notification.type === 2 }"
            @click="viewOrderDetails(notification)"
          >
            <div class="notification-item-header">
              <div class="notification-badge">
                <el-tag size="small" type="danger" v-if="!notification.read">新</el-tag>
                <el-tag size="small" type="primary" v-else>已读</el-tag>
                <el-tag size="small" type="warning" v-if="notification.type === 2">催单</el-tag>
                <el-tag size="small" type="success" v-if="notification.type === 1">新订单</el-tag>
              </div>
              <div class="notification-time">{{ formatTime(notification.timestamp) }}</div>
            </div>
            
            <!-- 新订单通知 -->
            <div class="notification-item-content" v-if="notification.type === 1">
              <div class="notification-item-title">
                新订单 #{{ notification.data.orderNumber }}
              </div>
              <div class="notification-item-info">
                <div class="notification-item-time">下单时间: {{ notification.data.orderTime }}</div>
                <div v-if="notification.needsDetails" class="notification-simple-hint">
                  点击查看完整订单详情
                </div>
              </div>
            </div>
            
            <!-- 催单通知 -->
            <div class="notification-item-content" v-else-if="notification.type === 2">
              <div class="notification-item-title">
                订单催单 #{{ notification.data.orderNumber }}
              </div>
              <div class="notification-item-info">
                <div>{{ notification.data.content }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="notification-empty" v-else>
          <el-empty description="暂无通知" />
        </div>
        <div class="notification-footer">
          <div class="connection-status">
            <el-tag 
              size="small" 
              :type="connectionStatusType"
            >
              {{ connectionStatusText }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Bell, Close } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { ElMessageBox, ElMessage } from 'element-plus'
import { 
  initWebSocket, 
  closeWebSocket, 
  getPendingNotifications, 
  getUnreadNotificationCount,
  markNotificationAsRead, 
  markAllNotificationsAsRead, 
  clearAllNotifications,
  connectionStatus
} from '@/utils/websocket'

const router = useRouter()
const appStore = useAppStore()
const popoverVisible = ref(false)

// 是否处于测试模式（开发环境显示测试按钮）
const isTestMode = ref(false)

// 获取通知列表
const notifications = computed(() => {
  return getPendingNotifications()
})

// 获取未读通知数量
const unreadCount = computed(() => {
  return getUnreadNotificationCount()
})

// 连接状态相关
const connectionStatusType = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      return 'success'
    case 'connecting':
      return 'warning'
    case 'disconnected':
      return 'danger'
    default:
      return 'info'
  }
})

const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      return '已连接'
    case 'connecting':
      return '连接中...'
    case 'disconnected':
      return '已断开'
    default:
      return '未知状态'
  }
})

// 处理通知铃铛点击
const handleBellClick = () => {
  // 显示通知面板
  popoverVisible.value = !popoverVisible.value
  
  // 如果打开通知面板，标记所有通知为已读
  if (popoverVisible.value && unreadCount.value > 0) {
    setTimeout(() => {
      markAllAsRead()
    }, 2000) // 延迟2秒后标记为已读
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  
  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
  
  // 如果是昨天
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
  
  // 其他时间
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 查看订单详情
const viewOrderDetails = (notification) => {
  // 标记为已读
  markNotificationAsRead(notification.id)
  
  console.log('点击通知，准备查看订单:', notification);
  
  // 提取订单ID
  let orderId;
  let orderNumber;
  
  // 检查数据结构，确保获取正确的订单ID和订单号
  if (notification.data) {
    orderNumber = notification.data.orderNumber; // 保存订单号用于显示
    
    if (notification.data.id) {
      orderId = notification.data.id;
    } else if (notification.data.orderNumber) {
      orderId = notification.data.orderNumber;
    }
  }
  
  // 如果从data中无法获取，则使用通知自身ID
  if (!orderId) {
    orderId = notification.id;
  }
  
  console.log('获取到订单ID:', orderId, '订单号:', orderNumber);
  
  // 关闭通知面板
  popoverVisible.value = false
  
  // 直接跳转到订单页面，让订单页面自己获取详细数据
  if (orderId) {
    try {
      // 添加时间戳防止路由相同不刷新
      const timestamp = Date.now();
      const query = {
        orderId: orderId,
        orderNumber: orderNumber,
        openDetail: true,
        _t: timestamp
      };
      
      console.log('跳转到订单详情:', query);
      
      // 使用更健壮的方式导航
      router.push({
        path: '/orders',
        query: query
      }).then(() => {
        console.log('导航到订单页面成功');
        
        // 触发订单详情打开事件，方便订单页面捕获
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('open-order-detail', { 
            detail: { 
              orderId, 
              orderNumber
            } 
          }));
        }, 300);
      }).catch(err => {
        console.error('导航到订单页面失败:', err);
        ElMessage.error('导航到订单页面失败，请手动查看订单列表');
      });
      
    } catch (error) {
      console.error('跳转到订单页面出错:', error);
      ElMessage.error('跳转失败，请手动查看订单列表');
    }
  } else {
    console.error('无法获取订单ID，无法跳转');
    ElMessage.warning('无法获取订单ID，请手动查看订单列表');
  }
}

// 标记所有通知为已读
const markAllAsRead = () => {
  markAllNotificationsAsRead()
}

// 清空所有通知
const clearAll = () => {
  clearAllNotifications()
}

// 关闭通知面板
const closeNotificationPanel = () => {
  popoverVisible.value = false
}

// 组件初始化时
onMounted(() => {
  const userId = appStore.userInfo?.id || 'anonymous'
  initWebSocket(userId, (message) => {
    console.log('订单通知组件收到消息:', message)
  })
  
  // 监听通知数据更新事件
  window.addEventListener('notification-data-updated', handleNotificationDataUpdate);
})

// 组件销毁时
onUnmounted(() => {
  closeWebSocket()
  // 移除事件监听
  window.removeEventListener('notification-data-updated', handleNotificationDataUpdate);
})

// 处理通知数据更新
const handleNotificationDataUpdate = (event) => {
  if (event && event.detail) {
    console.log('订单通知组件收到数据更新:', event.detail);
  }
}
</script>

<style scoped>
.notification-wrapper {
  position: relative;
  display: inline-flex;
  margin: 0;
  padding: 0;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 100%; /* 填充父容器高度 */
  line-height: 1; /* 确保没有额外行高影响垂直居中 */
  vertical-align: middle; /* 增加垂直对齐 */
}

/* 当有未读通知时添加摇动动画 */
@keyframes bell-shake {
  0% { transform: rotate(0); }
  2% { transform: rotate(5deg); }
  4% { transform: rotate(-5deg); }
  6% { transform: rotate(0); }
  100% { transform: rotate(0); }
}

.has-notifications {
  animation: bell-shake 3s infinite ease-in-out;
}

@keyframes bell-wave {
  0% { box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4); }
  70% { box-shadow: 0 0 0 8px rgba(245, 108, 108, 0); }
  100% { box-shadow: 0 0 0 0 rgba(245, 108, 108, 0); }
}

@keyframes bell-ring {
  0% { transform: rotate(0); }
  5% { transform: rotate(10deg); }
  10% { transform: rotate(-10deg); }
  15% { transform: rotate(8deg); }
  20% { transform: rotate(-8deg); }
  25% { transform: rotate(5deg); }
  30% { transform: rotate(-5deg); }
  35% { transform: rotate(0); }
  100% { transform: rotate(0); }
}

.notification-counter {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  font-size: 12px;
  padding: 0 3px;
  z-index: 5;
  box-shadow: 0 1px 2px rgba(0,0,0,0.2);
  transform: translate(30%, -30%); /* 调整位置，确保部分显示在铃铛外 */
}

.notification-bell {
  cursor: pointer;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
  box-sizing: border-box;
  width: 32px;
  height: 32px;
  position: relative;
  overflow: hidden;
}

/* 提升铃铛图标样式 */
.bell-icon {
  font-size: 20px;
  color: #606266;
  margin: 0;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
  display: flex; /* 确保图标居中 */
  align-items: center;
  justify-content: center;
}

/* 添加一个新的类用于有未读通知时的波纹效果 */
.has-notifications .notification-bell {
  animation: bell-wave 2s infinite;
}

/* 波纹背景效果 */
.has-notifications .notification-bell::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(245, 108, 108, 0.2);
  transform: scale(1);
  animation: ripple 2s infinite;
  z-index: 0;
}

@keyframes ripple {
  0% {
    transform: scale(0.85);
    opacity: 0.6;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.2;
  }
  100% {
    transform: scale(0.85);
    opacity: 0.6;
  }
}

.notification-bell::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: transparent;
  border-radius: 50%;
  transition: all 0.3s ease;
  z-index: 0;
}

.notification-bell:hover::before {
  background-color: rgba(255, 255, 255, 0.15); /* 使用白色背景，更适合暗色主题 */
}

.notification-bell:active::before {
  background-color: rgba(255, 255, 255, 0.25); /* 点击时加深颜色 */
}

/* 未读消息时添加铃铛摇动动画 */
.has-notifications .bell-icon {
  animation: bell-ring 6s 1s infinite;
  color: #409EFF; /* 未读消息时图标为蓝色 */
}

.notification-bell:hover .bell-icon {
  color: #409EFF; /* 悬停时变为蓝色 */
  transform: scale(1.05); /* 轻微放大 */
}

.notification-panel {
  display: flex;
  flex-direction: column;
  max-height: 480px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.notification-title {
  font-size: 16px;
  font-weight: bold;
}

.notification-actions {
  display: flex;
  gap: 10px;
}

.notification-content {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
}

.notification-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 0; /* 确保没有额外的间距 */
}

.notification-item:hover {
  background-color: #f9f9f9;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-item.reminder {
  border-left: 3px solid #e6a23c;
}

.notification-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.notification-badge {
  display: flex;
  gap: 5px;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-item-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 2px; /* 添加内边距 */
}

.notification-item-title {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
}

.notification-item-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-top: 5px; /* 增加与标题的间距 */
}

.notification-empty {
  padding: 30px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.notification-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  border-top: 1px solid #eee;
}

.connection-status {
  font-size: 12px;
}

.notification-item-status {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #e0e0e0;
  font-size: 13px;
  color: #606266;
}

.notification-simple-hint {
  margin-top: 8px;
  padding-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
  font-style: italic;
  border-top: 1px dashed #f0f0f0;
}

.order-items {
  margin-top: 5px;
}

.order-item-title {
  font-weight: 500;
  margin-top: 5px;
  color: #303133;
}

.order-item {
  padding: 2px 0;
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style>
/* 确保弹出框不会自动关闭 */
.notification-popover.el-popper {
  z-index: 2000 !important;
  padding: 0 !important;
  min-width: 300px !important; /* 保持适中的宽度 */
  max-width: 320px !important; /* 限制最大宽度 */
  border-radius: 4px !important;
}

.notification-popover.el-popper .el-popper__arrow {
  display: block !important;
}

/* 添加弹出框阴影效果 */
.notification-popover.el-popper {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  border: 1px solid #ebeef5 !important;
}

/* 自定义订单通知弹窗样式 */
.order-notification-popup {
  max-width: 320px !important;
  min-width: 300px !important;
}

.order-notification-popup .el-notification__content {
  text-align: left !important;
  margin: 5px 0 0 0 !important;
  font-size: 13px !important;
}

.order-notification-popup.reminder {
  background-color: #fdf6ec !important;
  border-color: #e6a23c !important;
}

.order-notification {
  display: flex !important;
  flex-direction: column !important;
  gap: 10px !important;
}

.order-info {
  display: flex !important;
  flex-direction: column !important;
  gap: 3px !important;
  font-size: 13px !important;
}

.order-action {
  display: none !important;
}

.view-btn {
  display: none !important;
}

.view-btn:hover {
  display: none !important;
}
</style> 